<?php
namespace app\admin\controller\v1;
use app\admin\Adminbase;

class Goods extends Adminbase 
{

    /**
     *获取商品分类
     * /admin/v1/goods/getGoodsCate
     * 需要登录
     * @is_need_login true
     */
    public function getGoodsCate(){

        try {
            $result =  model('GoodsCate')->getList(request()->userInfo['shop_id'],'*');

            $i=0;
            $cate_result=[];
            foreach ($result as $k=>$v){

                $arra_cate=json_decode($v,true);

                foreach ($arra_cate['childs'] as $key=>$value){
                        $i++;
                        $cate_result[$i]['label']=$value['name'];
                        $cate_result[$i]['value']=$value['id'];
                }
            }
            array_unshift($cate_result,["label"=>"请选择","value"=>""]);
            return $cate_result;
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
	
	/**
	* 添加或更新字表数据
	* /admin/v1/goods/addOrUpdateChilds
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function addOrUpdateChilds($goods_id,$goodsData,$specsData){
		$goodsData = json_decode($goodsData,true);
		$specsData = json_decode($specsData,true);
		try {
			//获取商品
			$goods = model('Goods')->get($goods_id);
			
			//为商品添加套餐内商品
			if($goodsData){
				$goods->goodsMeal()->where('id','not in', array_column($goodsData, 'id') )->delete();
				$goods->goodsMeal()->allowField(true)->saveAll($goodsData);
			}
			
			//为商品添加规格
			$goods->goodsSpecs()->where('id','not in',array_column($specsData,'id'))->delete();
			$specss = $goods->goodsSpecs()->allowField(true)->saveAll($specsData);
			foreach( $specss as $key=>$specs ){
				//为规格添加库存
				if( $res = $specs->stocks()->where('shop_id',$goods->shop_id)->find() ){
					$res->stock = $specs->stock ?: 0;
					$res->save();
				}else{
					$stock['shop_id'] = $goods->shop_id;
					$stock['specs_id'] = $specs->id;
					$stock['stock'] = $specs->stock ?: 0;
					$specs->stocks()->save($stock);
				}
				//为规格添加礼包
				if( ($giftBag = $specs['gift_bag'] ?? '-1') != '-1'){
					$specs->gifts()->where('specs_id',$specs->id)->delete();
					foreach( $giftBag as $k=>$gift ){
						unset($giftBag[$k]['id']);
						$giftBag[$k]['specs_id'] = $specs->id;
					}
					$specs->gifts()->allowField(true)->saveAll($giftBag);
				}
				//为规格设置收益
				if( ($draws = $specs['draws'] ?? '-1') != '-1' ){
					$specs->profits()->where('specs_id',$specs->id)->delete();
					foreach( $draws as $k=>$gift ){
						unset($draws[$k]['id']);
						$draws[$k]['specs_id'] = $specs->id;
					}
					$specs->profits()->allowField(true)->saveAll($draws);
				}
			}
			
			//返回成功
			return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	/**
	* 商品审核
	* /app/v2/Goods/approval
	* 需要登录 
	* @is_need_login true
	*@method post 
	*/
	public function approval($id,$status,$status_desc){
		try {
			$db = model('Goods');
			$result = $db->approval($id,$status,$status_desc);
			if(!$result){
				return $this->ReError( $db->errorInfo );
			}
			return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 商品进货审核
	* /admin/v1/Goods/purchaseApproval
	* 需要登录 
	* @is_need_login true
	*@method post 
	*/
	public function purchaseApproval($id){
		try {
			if(!$apply = model('goods_purchase')->where('status',0)->get($id)){
				return $this->ReError("没有找到申请记录！");
			}
			
			\Db::startTrans();
			//减总店库存
			$stocks = model("goods_specs_stock")
				->where('specs_id',$apply->specs_id)
				->where('shop_id',0)
				->where('(stock - frozen_stock) >= '.$apply->num)
				->find();
			if(!$stocks){
				\Db::rollback();
				return $this->ReError("该商品规格，库存不足".$apply->num);
			}else{
				$stocks->stock = ['dec', $apply->num];
				$stocks->save();
			}
			
			
			//添加库存
			$specsStock = model("goods_specs_stock")
				->where('specs_id',$apply->specs_id)
				->where('shop_id',$apply->shop_id)
				->find();
			if($specsStock){
				$specsStock->stock = ['inc', $apply->num];
				$specsStock->save();
			}else{
				model("goods_specs_stock")->save([
					'shop_id'=>$apply->shop_id,
					'specs_id'=> $apply->specs_id,
					'stock'=> $apply->num,
				]);
			}
			
			$apply->status = 1;
			$apply->apply_user = request() ->userInfo['user_name'];
			$apply->apply_time = date('Y-m-d H:i:s');
			$apply->save();
			
			//返佣金
			$res = model('user')->backPurchaseBrokerage($apply);
						
			\Db::commit();
			return $this->ReSucess();	
		} catch (\Exception $e) {
			\Db::rollback();
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 添加商品状态数据
	* /admin/v1/Goods/addGoodsStatus
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function addGoodsStatus($id){
		try {
			//获取申请记录
			if(!$apply = model('goods_purchase')->where('status',0)->get($id)){
				return $this->ReError("没有找到申请记录！");
			}
			
			//添加状态
			$status = model("goods_status")
				->where('shop_id',$apply->shop_id)
				->where('goods_id',$apply->goods_id)
				->find();
			if($status){
				$status->is_del = 0;
				$status->status = 1;
				$status->save();
			}else{
				model("goods_status")->save([
					'status'=>1,
					'shop_id'=>$apply->shop_id,
					'goods_id'=> $apply->goods_id,
				]);
			}
			return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 更新商品状态 - 上下架
	* /admin/v1/Goods/updateGoodsStatus
	* 需要登录 
	* @is_need_login true
	* @method post
	*/
	public function updateGoodsStatus($id,$type){
		try {
			$shop_id = request()->userInfo['shop_id'];
			if( !$goods = model("goods")->get($id) ){
				return $this->ReError("没有找到商品！");
			}	
			if($goods->shop_id > 0){
				$goods->status = $type==1 ? 1 : 2;
				$goods->save();
			}else{
				$status = model("goods_status")->where('shop_id',$shop_id)->where('goods_id',$id)->find();
				$status->status = $type==1 ? 1 : 2;
				$status->save();
			}
			return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}

    /**
     * 添加商品抢购规格
     * /admin/v1/goods/addGoodSpecs
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function addGoodSpecs($goods_id,$specsData){

        $specsData = json_decode($specsData,true);
        try {
            //获取商品
            $goods = model('Goods')->get($goods_id);

            if($goods){
                model('Goods')->where(['id'=>$goods_id])->update(['is_benefit'=>1]);
            }

            //为商品添加规格
            $goods->goodsSpecs()->where('id','not in', array_column($specsData, 'id') )->delete();
            $specss = $goods->goodsSpecs()->allowField(true)->saveAll($specsData);
            //为规格添加库存
            foreach( $specss as $key=>$specs ){
                if( $res = $specs->stocks()->where('shop_id',$goods->shop_id)->find() ){

                    $res->stock = $specs->stock ?: 0;
                    $res->benefit_stock = $specs->benefit_stock ?: 0;
                    $res->is_benefit_specs = $specs->is_benefit_specs;
                    $res->save();
                }else{

                    $stock['shop_id'] = $goods->shop_id;
                    $stock['specs_id'] = $specs->id;
                    $stock['stock'] = $specs->stock ?: 0;
                    $stock['benefit_stock'] = $specs->benefit_stock ?: 0;
                    $stock['is_benefit_specs'] = $specs->is_benefit_specs;
                    $specs->stocks()->save($stock);
                }
            }

            //返回成功
            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 开始优惠抢购设置
     * /admin/v1/goods/startGoodBenefit
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function startGoodBenefit($goods_id){

        try {
            //获取商品
            $goods = model('Goods')->get($goods_id);

            if($goods){
                model('Goods')->where(['id'=>$goods_id])->update(['is_benefit'=>1]);
            }

            //返回成功
            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 停止优惠抢购设置
     * /admin/v1/goods/stopGoodBenefit
     * 需要登录
     * @is_need_login true
     * @method post
     */
    public function stopGoodBenefit($goods_id){

        try {
            //获取商品
            $goods = model('Goods')->get($goods_id);

            if($goods){
                model('Goods')->where(['id'=>$goods_id])->update(['is_benefit'=>0]);
            }

            //返回成功
            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
	
}



